﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
//using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Uranus.WeiStationAPI.Models;

namespace Uranus.WeiStationAPI
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();
            //AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);

            // 添加一个转换器 IsoDateTimeConverter，其用于日期数据的序列化和反序列化
            var dateTimeConverter = new IsoDateTimeConverter();
            dateTimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
            serializerSettings.Converters.Add(dateTimeConverter);
            // 清除全部 Formatter（默认有 4 个，分别是：JsonMediaTypeFormatter, XmlMediaTypeFormatter, FormUrlEncodedMediaTypeFormatter, JQueryMvcFormUrlEncodedFormatter）
            //GlobalConfiguration.Configuration.Formatters.Clear();
            // 如果请求 header 中有 accept: text/html 则返回这个新建的 JsonMediaTypeFormatter 数据
            var jsonFormatter = new JsonMediaTypeFormatter();
            jsonFormatter.SerializerSettings = serializerSettings;
            // jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 
            jsonFormatter.MediaTypeMappings.Add(new RequestHeaderMapping("accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true, new MediaTypeHeaderValue("text/html")));
            GlobalConfiguration.Configuration.Formatters.Insert(0, jsonFormatter);
            // 请求 url 中如果带有参数 xml=true，则返回 xml 数据
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
            // 请求 url 中如果带有参数 jsonp=true，则返回支持 jsonp 协议的数据（具体实现参见 MyJsonFormatter.cs）
            JsonpMediaTypeFormatter formatter = new JsonpMediaTypeFormatter();
            formatter.MediaTypeMappings.Add(new QueryStringMapping("jsonp", "true", "application/javascript"));
            GlobalConfiguration.Configuration.Formatters.Add(formatter);


            GlobalConfiguration.Configuration.Filters.Add(new ApiExceptionFilter());

            SetControllerProperty();
        }

        private void SetControllerProperty()
        {
            //反射自身 查出有特殊标记的   
            Type[] s = System.Reflection.Assembly.GetExecutingAssembly().GetTypes();
            foreach (Type type in s)
            {
                if (type.BaseType != null && type.BaseType.Name == "BaseController")
                {
                    System.Reflection.MethodInfo[] methodInfos = type.GetMethods();
                    foreach (MethodInfo methodInfo in methodInfos)
                    {
                        var attr = methodInfo.GetCustomAttributes(typeof(Uranus.WeiStationAPI.App_Start.UserStateAttribute), false).FirstOrDefault();
                        if (attr != null)
                        {
                            Uranus.WeiStationAPI.App_Start.UserStateAttribute attribute =
                                (Uranus.WeiStationAPI.App_Start.UserStateAttribute)attr;
                            Uranus.WeiStationAPI.Models.ControllerProperty.ControllerDtos.Add(new ControllerDTO()
                                {
                                    controllername = type.FullName.ToLower(),
                                    methodname = methodInfo.Name.ToLower(),
                                    VisitUserStateEnum = attribute.VisitUserStateEnum,
                                    enEncryption = attribute.EnEncryption,
                                    enAuthHuifu = attribute.EnAuthHuifu
                            });
                        }
                    }
                }
            }
        }
    }
}